﻿using System;
using System.Collections.Generic;

namespace uebung_ToDictionary.source
{
    public class StringExtension
    {
        public static IDictionary<String, String> ToDictionary(String s)
        {
            var settings = SplitIntoSettings(s);
            var parameterValues = SplitIntoParameterValues(settings);
            return CreateDictionary(parameterValues);
        }

        internal static IEnumerable<String> SplitIntoSettings (String config)
        {
            if (config == null)
            {
                throw new ArgumentException("null is not allowed as parameter");
            }
            var separator = new[] { ';' };
            var settings = config.Split(separator, StringSplitOptions.RemoveEmptyEntries);

            var settingsList = new List<String>(settings);
            return settingsList;
        }

        internal static IEnumerable<Tuple<String, String>> SplitIntoParameterValues (IEnumerable<String> settings)
    {
            var parameterValues = new List<Tuple<String, String>>();
            var enumerator = settings.GetEnumerator();
            while (enumerator.MoveNext())
            {
                var parameterValue = enumerator.Current;
                var indexEquals = parameterValue.IndexOf('=');
                var parameter = GetParameter(parameterValue, indexEquals);
                var value = GetValue(parameterValue, indexEquals);
                var tuple = Tuple.Create(parameter, value);
                parameterValues.Add(tuple);

            }
            return parameterValues;
    }

        internal static IDictionary<String, String> CreateDictionary (IEnumerable<Tuple<String, String>> parameterValues)
        {
            var dictionary = new Dictionary<string, string>();
            var enumerator = parameterValues.GetEnumerator();
            while (enumerator.MoveNext())
            {
                var parameterValue = enumerator.Current;
                dictionary.Add(parameterValue.Item1,parameterValue.Item2);
            }
            return dictionary;
        }

        private static String GetParameter(String parameterValue, int indexEquals)
        {
            String parameter = indexEquals != -1 ? parameterValue.Substring(0, indexEquals).Trim() : parameterValue.Trim();
            var parameterEmpty = parameter.Length == 0;
            
            if (parameterEmpty)
            {
                throw new ArgumentException("no parameter given");
            }
            return parameter;
        }

        private static String GetValue(String parameterValue, int indexEquals)
        {
            String value = indexEquals != -1 ? parameterValue.Substring(indexEquals + 1) : "";
            return value;
        }
    }
}
